package com.eduardcapell.lopodder.gui;

import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;

import javax.swing.table.DefaultTableModel;

import com.eduardcapell.lopodder.beans.Feed;
import com.eduardcapell.lopodder.beans.FeedElement;

public class FeedListTableModel extends DefaultTableModel {

    public static final int COLUMN_STATUS = 0;
    public static final int COLUMN_NAME = 1;
    public static final int COL_URL = 2;
    public static final int COL_NEW_ELEMS = 3;
    public static final String[] COLUMN_NAMES = {
        "Status",
        "Name",
        "URL",
        "New elements"
    };
    private List<Feed> feeds;

    public FeedListTableModel(List<Feed> feeds) {
        this.feeds = feeds;
        Collections.sort(feeds);
    }

    @Override
    public int getColumnCount() {
        return COLUMN_NAMES.length;
    }

    @Override
    public String getColumnName(int i) {
        return COLUMN_NAMES[i];
    }

    @Override
    public int getRowCount() {
        if (feeds == null || feeds.size() == 0) {
            return 0;
        }

        return feeds.size();
    }

    @Override
    public Object getValueAt(int row, int column) {
        if (feeds == null || feeds.size() == 0) {
            return null;
        }

        Feed f = feeds.get(row);
        switch (column) {
            case COLUMN_STATUS:
                return f.getStatus().toString();
            case COL_URL:
                return f.getUrl().toString();
            case COLUMN_NAME:
                return f.getName();
            case COL_NEW_ELEMS:
                List<FeedElement> elems = f.getElements();
                Iterator<FeedElement> it = elems.iterator();
                while (it.hasNext()) {
                    FeedElement fe = it.next();
                    if (!fe.isDownloaded()) {
                        return true;
                    }
                }
                return false;
            default:
                return "N/A";
        }
    }

    @Override
    public Vector getDataVector() {
        return new Vector(feeds);
    }

    @Override
    public boolean isCellEditable(int row, int column) {
        return false;
    }

    @Override
    public Class<?> getColumnClass(int i) {
        switch (i) {
            case COL_NEW_ELEMS:
                return Boolean.class;
            case COLUMN_STATUS:
                return String.class;
            case COL_URL:
            case COLUMN_NAME:
            default:
                return String.class;
        }
    }

    public Feed getFeedInRow(int row) {
        if (feeds == null || feeds.size() <= 0) {
            return null;
        }

        if (row >= feeds.size()) {
            return null;
        }

        return feeds.get(row);
    }
}
